<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="verify-v1" content="+lrjymYXl9dYUpiloRD4vYSuiXh9VknJSi7FuzQ6WvU=" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>gTime</title>
  <link type="text/css" rel="stylesheet" href="/stylesheets/gtime.css" />
  <link rel="shortcut icon" href="static/favicon.ico" />
  <script type="text/javascript" src="./static/json2.js"></script>
  <script type="text/javascript" src="./static/rpchelpers.js"></script>
  <script type="text/javascript" src="./static/xslhelpers.js"></script>
  <script type="text/javascript" src="./static/tableedit.js"></script>
  <script type="text/javascript" src="./static/datehelpers.js"></script>


  <script type="text/javascript">

  // Server object that will contain the callable methods
  var server = {};
  var prevSelCal = null;

  // Insert 'Search' as the name of a callable method
  InstallFunction(server, 'Search');

  // Handy "macro"
  function $(id){
    return document.getElementById(id);
  }


  function clearResults() {
	$('searchResults').innerHTML = '';
  }

  // Client function that calls a server rpc and provides a callback
  function doSearch() {
	clearResults();
	showProgress(true);
	var sr = new Object();
	sr.calendarId = $('calendar_id').value;
	sr.startDate = $('start_date').value;
	sr.endDate = $('end_date').value;
	sr.queryString = $('query_string').value;
	sr.defaultRate = $('rate').value;
	server.Search(sr, onSearchSuccess);
  }

  // Callback for after a successful doSearch
  function onSearchSuccess(response) {
	showProgress(false);
	var elem = $('searchResults');
	if (response) {
		elem.innerHTML = response;
		elem.addEventListener("change", doInputChanged, false);	//TODO(carterm)- not working
	}
	else
		elem.innerHTML = '<p class="alert">Error searching your calendar; make sure both start date and end date are valid and that you have authorized access to your calendar.</p>';
  }

  function showProgress(bShow) {
	displayElement($('rpc_progress'), bShow);
  }


  function displayElement(el, bShow) {
	if (bShow)	
	  el.style.display = 'block';
	else
	  el.style.display = 'none';
  }


  // el is the div element; TODO(carterm): honor timezone of the selected calendar
  function selectCalendar(calendarId, el, calendarColor) {
	if (!calendarColor) c = '#2952A3';
	else c = calendarColor;
	$('embedded_calendar').src = 'http://www.google.com/calendar/embed?height=600&wkst=1&bgcolor=%23FFFFFF&src=' + calendarId + '&color=' + escape(c) + '&ctz=America%2FLos_Angeles';
	$('calendar_id').value = calendarId;
	var sb = $('search_button');
	if (el) {
		el.className = 'selected-calendar';	
		if (prevSelCal != null)		// if a prior selected calendar exists, deselect it
			prevSelCal.className = 'deselected-calendar';
		prevSelCal = el;
		sb.value = "Search " + $(calendarId).firstChild.nodeValue;
	}
	else sb.value = "Search " + calendarId;
	sb.disabled = false;
	$('calendar_list').style.display = 'none';
  }

  function setHover(el, bOn) {
	if (bOn) {
		el.style.cursor = 'pointer';
		el.style.textDecoration = 'underline'; 
	}
	else
	{
		el.style.cursor = 'default';
		el.style.textDecoration = 'none';
	}
	
  }

function toggleChecks()
{
  // Cycle through all of the check boxes
  var elems = document.getElementsByTagName('INPUT');
  var checkbox_checked = document.getElementById('toggle_checks').checked;

  for (var prop in elems)
  {
    if (elems[prop].type == 'checkbox')
    {
      elems[prop].checked = checkbox_checked;
    }
  }
}

function markPaid(bPaid)
{
  // make the payment amount match the fee amount for all those rows checked.
  var elems = document.getElementsByTagName('INPUT');
  var total = 0.0;
  for (var prop in elems) {
	var e = elems[prop];
    if (e.type == 'checkbox' && e.parentNode.className == 'list-row') {
	  var rowNode = ancestor(e, 'TR');
	/*
	  var cbTD = e.parentNode;
	  var rowNode = cbTD.parentNode; //todo(testing)
	*/
	  var feeNode = getFirstChild(rowNode.getElementsByClassName('fee')[0]);
	  var payNode = getFirstChild(rowNode.getElementsByClassName('payment')[0]);
	  var checkbox_checked = e.checked;
	  if (checkbox_checked) {
		  if (bPaid) payNode.data = feeNode.data;
		  else payNode.data = "0.0";
		
      }
	  total += parseFloat(payNode.data);
    }
  }
  assignTotal(total);  
}

function calculateTotal()
{
  var elems = document.getElementsByTagName('INPUT');
  var total = 0.0;
  for (var prop in elems) {
	var e = elems[prop];
    if (e.type == 'checkbox' && e.parentNode.className == 'list-row') {
	  var rowNode = ancestor(e, 'TR');
	  var payNode = getFirstChild(rowNode.getElementsByClassName('payment')[0]);
	  total += parseFloat(payNode.data);
    }
  }
  assignTotal(total);  
}


function getFirstChild(n)
{
  var x = n.firstChild;
  while (x.nodeType!=3)
  {
    x = x.nextSibling;
  }
  return x;
}

function ancestor(who,tag) {
  while(who){
    if(who.nodeName==tag) return who;
    who=who.parentNode;
  }
  return false;
}

function assignTotal(total) {
	var totalNode = $('total_payments');
	totalNode.firstChild.nodeValue = total.toString();
}

function buildStatementFromRows()
{
  var statement = new Object();
  var lines = new Array();
  var totalHours = 0.0;
  var totalFees = 0.0;
  var totalPayments = 0.0;
  var elems = document.getElementsByTagName('INPUT');
  var i = 0;

  for (var prop in elems) 
  {
	var e = elems[prop];
    if (e.type == 'checkbox' && e.parentNode.className == 'list-row') 
	{
	  var checkbox_checked = e.checked;
	  if (checkbox_checked) 
	  {
		var rowNode = e.parentNode.parentNode;
		var line = new Object();
		// line.desc = rowNode.childNodes[2].firstChild.nodeValue + rowNode.childNodes[14].firstChild.nodeValue; //TODO(carterm) strip regex matches
		line.date = rowNode.childNodes[4].firstChild.nodeValue; //TODO(carterm) remove hardcoded values
		line.desc = rowNode.childNodes[6].firstChild.nodeValue;
		line.where = rowNode.childNodes[8].firstChild.nodeValue;
		line.rate = rowNode.childNodes[10].firstChild.nodeValue;
		line.duration = rowNode.childNodes[12].firstChild.nodeValue; 
		line.fee = rowNode.childNodes[14].firstChild.nodeValue; 
		line.payment = rowNode.childNodes[16].firstChild.nodeValue;
		lines[i++] = line;
		totalHours += parseFloat(line.duration);
		totalFees += parseFloat(line.fee);
	    totalPayments += parseFloat(line.payment);
      }
    }
  }	
  statement.lines = lines;
  statement.header = 'Click Settings to specify this header.';
  statement.clientName = 'Type client name/address here.';
  var now = new Date();
  var month = now.getMonth() + 1;
  var day = now.getDate();
  var year = now.getFullYear();
  statement.date = month + "/" + day + "/" + year;
  statement.totalHours = totalHours.toString();
  statement.totalFees = totalFees.toString();
  statement.totalPayments = totalPayments.toString();
  statement.balance = (totalFees - totalPayments).toString();
  return statement;	
}

function jsonifyStatement(elName){
  var s = buildStatementFromRows();
  $(elName).value = JSON.stringify(s);
}

function toggle(el)
{
	var e = $(el);
	if (e.style.display == '' || e.style.display == 'none')
		e.style.display = 'inline';
	else
		e.style.display = 'none';	
}

function doOnLoad(calendarId)
{
	var el = $(calendarId);
	selectCalendar(calendarId, el);
	
	//default to last 30 days	
	el = $('start_date');
	if (el.value == '')
		el.value = 't-30';
	parseDate(el);
	el = $('end_date');
	if (el.value == '')
		el.value = 't';
	parseDate(el);
}

function doInputChanged() {
	calculateTotal();
}

</script>

</head>
	{% if calendar_id %}
		<body onload="doOnLoad('{{ calendar_id }}')">
	{% else %}
		<body>
	{% endif %}
	{% include "header.html" %}
	<div id="body">	
		<div id="center_content">
			{% if message_text %}
		    <div id="message" class="alert">{{ message_text }}</div>
			{% endif %}	
			<div id="searchbox">
				<table>
					<tr>
						<td><div id="logo"></div></td>
						<td><span class="example">start date</span><br/><input id="start_date" type="text" size="10" name="start_date" value="{{start_date}}" onblur="parseDate(this)"></td>
						<td><span class="example">end date</span><br/><input id="end_date" type="text" size="10" name="end_date" value="{{end_date}}" onblur="parseDate(this)"></td>
						<td><span class="example">query</span><br/><input id="query_string" type="text" size="30" name="query_string" value="{{query}}"></td>
					</tr>
					<tr>
						<td></td>
						<td colspan=3><input id="search_button" disabled name="search_button" type="submit" value="Search My Calendar" onclick="doSearch()">
							<a href="javascript:toggle('calendar_list')">Calendars<small>▼</small></a><br/>
							<div id="calendar_list">
								{% spaceless %}
								{% for calendar in calendar_list %}
								<div id="{{ calendar.tail }}" class="deselected-calendar" 
								onclick="selectCalendar('{{ calendar.tail }}', this, '{{ calendar.color }}')" 
								style="color: {{ calendar.color }}"
								onmouseout="setHover(this, 0)" onmouseover="setHover(this, 1)">{{ calendar.title }}</div>
							    {% endfor %}
								{% endspaceless %}
							</div>			
						</td>
					</tr>
				</table>
			    <div id="hidden_fields">
					<input id="calendar_id" type="text" name="calendar_id" value="{{calendar_id}}" size="15">
					<input id="rate" type="text" name="rate" value="{{ settings.hourly_rate }}" size="7">
				</div>	
			</div>
			<div id="resultbox">
		    	<div id="searchResults"></div>
		 	</div>
			<iframe id="embedded_calendar" style=" border-width:0 " width="800" height="600" frameborder="0" scrolling="no"></iframe>		
		</div>
	</div>
	{% include "footer.html" %}
  </body>
</html>